package cn.wolfcode.shop.web.controller;

import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.redis.RedisServer;
import cn.wolfcode.shop.redis.SeckillGoodKeyPrefix;
import cn.wolfcode.shop.web.util.AccessLimit;
import cn.wolfcode.shop.web.util.VerifyCodeImgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class VerifyCodeController {
    @Autowired
    private RedisServer redisServer;
    @RequestMapping("/getVerifyCodeImg")
    @ResponseBody
    @AccessLimit(seconds = 5,maxCount = 5,needLogin = true)
    public void getVerifyCodeImg(HttpServletResponse response,User user,Long goodId){
        if(user==null){
            return ;
        }
        String verifyCodeExp = VerifyCodeImgUtil.generateVerifyCode();
        Integer result = VerifyCodeImgUtil.calc(verifyCodeExp);
        redisServer.set(SeckillGoodKeyPrefix.SECKILL_VERIFYCODE_RESULT,user.getId()+":"+goodId,result);
        BufferedImage img = VerifyCodeImgUtil.createVerifyCodeImg(verifyCodeExp);
        try {
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(img,"JPEG",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
